package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.exception.BusinessException;
import com.alibaba.fastjson.JSONArray;
import com.unlcn.ils.sales.backend.bo.OrderTagBO;
import com.unlcn.ils.sales.base.mapper.SaleOrderTagMapper;
import com.unlcn.ils.sales.base.model.SaleOrderTag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * Created by houjianhui on 2017/5/27.
 */
@Service
public class OrderTagServiceImpl implements OrderTagService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderTagServiceImpl.class);

    @Autowired
    private SaleOrderTagMapper orderTagMapper;

    @Override
    public Integer save(String bo, Integer saleOrderId) throws Exception {
        LOGGER.info("OrderTagServiceImpl.save params OrderTagBO: {}", bo);
        if (StringUtils.isBlank(bo)) {
            LOGGER.info("OrderTagServiceImpl.save params OrderTagBO must be not null");
            throw new IllegalArgumentException("销售订单标签信息不能为空");
        } else if (Objects.equals(saleOrderId, null) || Objects.equals(saleOrderId, "")) {
            LOGGER.info("OrderTagServiceImpl.save params saleOrderId must be not null");
            throw new IllegalArgumentException("销售订单ID不能为空");
        }

        List<OrderTagBO> tagBOS = JSONArray.parseArray(bo, OrderTagBO.class);
        if (CollectionUtils.isEmpty(tagBOS)) {
            LOGGER.info("OrderTagServiceImpl.save tagBOS must be not null");
            throw new IllegalArgumentException("销售订单标签信息不能为空");
        }
        tagBOS.stream().forEach(val -> {
            val.setSaleOrderId(saleOrderId);
            SaleOrderTag tag = new SaleOrderTag();
            BeanUtils.copyProperties(val, tag);
            try {
                orderTagMapper.insertSelective(tag);
            } catch (Exception e) {
                LOGGER.error("OrderTagServiceImpl.save error: {}", e);
                throw new BusinessException("保存销售订单标签信息异常");
            }
        });

        return null;
    }
}
